
import { getToken } from './auth'
import axios from 'axios'

axios.defaults.timeout = 10000

// axios.defaults.baseURL = 'http://192.168.58.89:11109/'
axios.defaults.baseURL = 'http://192.168.72.26:11109/'
// axios.defaults.baseURL = 'http://192.168.66.148:11109/'
// axios.defaults.baseURL = process.env.VUE_APP_URL

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 每次发送请求之前携带token
    const token = getToken()
    if (token) {
      // 添加headers
      config.headers.token = `${token}`
      config.headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    } else {
      config.headers = { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
    }

    return config
  },
  error => {
    return Promise.error(error)
  })

// 接收响应拦截器
axios.interceptors.response.use(response => {
  if (response.data.code === 401) {
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('level')
    sessionStorage.removeItem('href')
    sessionStorage.removeItem('userName')
    this.$router.push('/login')
  }
  return response
},
error => {
  return Promise.reject(error)
})

//
// get方法，对应get请求
export function get (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

//  post方法，对应post请求
export function post (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })
}
